import { configureStore } from '@reduxjs/toolkit'
import { systemReducer } from './features/systemSlice'
import { getItem, setItem } from '@/shared/storage'

const REDUX_STATE_KEY = 'REDUX_STATE'

const saveState = (store) => (next) => (action) => {
  window.addEventListener('beforeunload', () => setItem(REDUX_STATE_KEY, store.getState()))
  return next(action)
}

export default configureStore({
  reducer: {
    system: systemReducer,
  },
  middleware: [saveState],
  preloadedState: getItem(REDUX_STATE_KEY),
})
